<template>
  <div class="add-route-form">
    <a-form
      :model="formState"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <a-form-item label="路线名称" name="routeName">
        <a-input v-model:value="formState.routeName" placeholder="请输入路线名称" />
      </a-form-item>

      <a-form-item label="路线信息" name="routeInfo">
        <a-textarea
          v-model:value="formState.routeInfo"
          placeholder="请输入路线详细信息"
          :rows="4"
        />
      </a-form-item>

      <a-form-item label="花费时间" name="spendTime">
        <a-input v-model:value="formState.spendTime" placeholder="如：3-5天" />
      </a-form-item>

      <a-form-item label="适宜时间" name="suitableTime">
        <a-input v-model:value="formState.suitableTime" placeholder="如：春季、夏季" />
      </a-form-item>

      <a-form-item label="沿途景点" name="alongScenics">
        <a-select
          v-model:value="formState.alongScenics"
          mode="multiple"
          placeholder="请选择沿途景点"
          style="width: 100%"
          :loading="scenicsLoading"
          show-search
          :filter-option="false"
          @search="handleScenicSearch"
        >
          <a-select-option v-for="scenic in availableScenics" :key="scenic.id" :value="scenic.id">
            <div style="display: flex; align-items: center; gap: 8px">
              <img
                v-if="scenic.coverImage"
                :src="scenic.coverImage"
                :alt="scenic.scenicName"
                style="width: 24px; height: 24px; border-radius: 4px; object-fit: cover"
              />
              <span>{{ scenic.scenicName }}</span>
            </div>
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="路线标签" name="routeTags">
        <a-select
          v-model:value="formState.routeTags"
          mode="multiple"
          placeholder="请选择路线标签"
          style="width: 100%"
          :loading="tagsLoading"
        >
          <a-select-option v-for="tag in availableTags" :key="tag.id" :value="tag.tagName">
            {{ tag.tagName }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="路线封面图片" name="routeCoverImage">
        <a-upload
          v-model:file-list="fileList"
          :before-upload="beforeUpload"
          list-type="picture-card"
          :max-count="1"
          accept="image/*"
          @change="handleUploadChange"
        >
          <div v-if="fileList.length < 1">
            <UploadOutlined />
            <div style="margin-top: 8px">上传封面图片</div>
          </div>
        </a-upload>
        <div style="color: #666; font-size: 12px; margin-top: 4px">
          支持 JPG、PNG、WEBP 格式，文件大小不超过 2MB
        </div>
      </a-form-item>

      <a-form-item :wrapper-col="{ offset: 6, span: 18 }">
        <a-space>
          <a-button type="primary" html-type="submit" :loading="loading">
            <PlusOutlined />
            添加路线
          </a-button>
          <a-button @click="resetForm">
            <ReloadOutlined />
            重置表单
          </a-button>
          <a-button @click="handleCancel">
            <CloseOutlined />
            取消
          </a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import type { UploadFile, UploadChangeParam } from 'ant-design-vue'
import { PlusOutlined, UploadOutlined, ReloadOutlined, CloseOutlined } from '@ant-design/icons-vue'
import { addRoute } from '@/api/routeController'
import { getListScenicVo } from '@/api/scenicController'
import { listTag } from '@/api/tagController'

const emit = defineEmits<{
  success: []
  cancel: []
}>()

const loading = ref(false)
const scenicsLoading = ref(false)
const tagsLoading = ref(false)
const fileList = ref<UploadFile[]>([])
const availableScenics = ref<API.ScenicVO[]>([])
const availableTags = ref<API.TagVO[]>([])

const formState = reactive({
  routeName: '',
  routeInfo: '',
  spendTime: '',
  suitableTime: '',
  alongScenics: [] as number[],
  routeTags: [] as string[],
  routeCoverImage: undefined as File | undefined,
})

const rules = {
  routeName: [
    { required: true, message: '请输入路线名称', trigger: 'blur' },
    { min: 2, max: 50, message: '路线名称长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  routeInfo: [
    { required: true, message: '请输入路线信息', trigger: 'blur' },
    { min: 10, max: 1000, message: '路线信息长度在 10 到 1000 个字符', trigger: 'blur' },
  ],
  spendTime: [{ required: true, message: '请输入花费时间', trigger: 'blur' }],
  suitableTime: [{ required: true, message: '请输入适宜时间', trigger: 'blur' }],
  alongScenics: [
    { required: true, message: '请选择至少一个沿途景点', trigger: 'change' },
    { type: 'array', min: 1, message: '请选择至少一个沿途景点', trigger: 'change' },
  ],
}

// 获取景点列表
const getAvailableScenics = async (searchValue = '') => {
  try {
    scenicsLoading.value = true
    const res = await getListScenicVo({
      scenicName: searchValue || undefined,
      pageSize: 50, // 获取更多景点用于选择
    })
    if (res.data.code === 200 && res.data.data) {
      availableScenics.value = res.data.data.records ?? []
    }
  } catch (error) {
    console.error('获取景点列表失败:', error)
    message.error('获取景点列表失败')
  } finally {
    scenicsLoading.value = false
  }
}

// 获取标签列表
const getAvailableTags = async () => {
  try {
    tagsLoading.value = true
    const res = await listTag({})
    const responseData = res as { data: API.BaseResponseListTagVO }
    if (responseData.data?.code === 200 && responseData.data?.data) {
      availableTags.value = responseData.data.data ?? []
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
    message.error('获取标签列表失败')
  } finally {
    tagsLoading.value = false
  }
}

// 搜索景点
const handleScenicSearch = (value: string) => {
  getAvailableScenics(value)
}

// 图片上传前的验证
const beforeUpload = (file: File) => {
  console.log('🔍 beforeUpload 被调用:', file)

  const isJpgOrPng =
    file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp'
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG/WEBP 格式的图片!')
    return false
  }
  const isLt2M = (file.size || 0) / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!')
    return false
  }

  // 直接在这里设置文件，因为 beforeUpload 返回 false 时 originFileObj 可能不可用
  formState.routeCoverImage = file
  console.log('✅ 在 beforeUpload 中直接设置图片文件:', file.name)

  return false // 阻止自动上传，我们手动处理
}

// 图片上传变化处理
const handleUploadChange = (info: UploadChangeParam) => {
  console.log('🔍 handleUploadChange 被调用:', info)
  console.log('📁 文件状态:', info.file.status)
  console.log('📄 原始文件对象:', info.file.originFileObj)
  console.log('📄 文件对象本身:', info.file)

  fileList.value = [...info.fileList]

  if (info.file.status === 'removed') {
    formState.routeCoverImage = undefined
    console.log('🗑️ 图片已移除')
    return
  }

  // 如果在 beforeUpload 中还没有设置文件，尝试从这里设置
  if (!formState.routeCoverImage) {
    const fileObj = info.file.originFileObj || info.file
    if (fileObj && fileObj instanceof File) {
      formState.routeCoverImage = fileObj
      console.log(
        '✅ 在 handleUploadChange 中设置路线封面图片:',
        fileObj.name,
        '大小:',
        fileObj.size,
      )
    } else {
      console.warn('⚠️ 无法从 handleUploadChange 获取有效的文件对象')
    }
  } else {
    console.log('ℹ️ 图片文件已在 beforeUpload 中设置')
  }
}

// 表单提交
const onFinish = async () => {
  loading.value = true

  try {
    console.log('🚀 开始提交路线数据')
    console.log('📋 表单状态:', formState)
    console.log('🖼️ 图片文件详情:', {
      file: formState.routeCoverImage,
      name: formState.routeCoverImage?.name,
      size: formState.routeCoverImage?.size,
      type: formState.routeCoverImage?.type,
      isFile: formState.routeCoverImage instanceof File,
    })

    // 如果没有图片但有文件列表，尝试从文件列表获取
    if (!formState.routeCoverImage && fileList.value.length > 0) {
      const firstFile = fileList.value[0]
      const fileObj = firstFile.originFileObj || firstFile
      if (fileObj && fileObj instanceof File) {
        formState.routeCoverImage = fileObj
        console.log('🔄 从文件列表中恢复图片文件:', fileObj.name)
      }
    }

    const response = await addRoute(formState)

    if (response.data.code === 200) {
      message.success('路线添加成功！')
      resetForm()
      emit('success')
    } else {
      message.error('添加失败：' + (response.data.message || '未知错误'))
    }
  } catch (error) {
    console.error('提交失败:', error)
    message.error('提交失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 表单提交失败
const onFinishFailed = (errorInfo: {
  errorFields: Array<{ name: string[]; errors: string[] }>
}) => {
  console.log('Failed:', errorInfo)
  message.error('请检查表单填写是否正确')
}

// 重置表单
const resetForm = () => {
  formState.routeName = ''
  formState.routeInfo = ''
  formState.spendTime = ''
  formState.suitableTime = ''
  formState.alongScenics = []
  formState.routeTags = []
  formState.routeCoverImage = undefined
  fileList.value = []
}

// 取消操作
const handleCancel = () => {
  resetForm()
  emit('cancel')
}

// 组件挂载时获取数据
onMounted(() => {
  getAvailableScenics()
  getAvailableTags()
})
</script>

<style scoped>
.add-route-form {
  padding: 24px;
  background: #fff;
  border-radius: 8px;
}

.ant-upload-select-picture-card {
  width: 104px;
  height: 104px;
}

:deep(.ant-select-selection-item) {
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
